from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response

from apps.goods.models import SKUImage, SKU
from celery_tasks.detail.tasks import get_detail_html
from meiduo_mall import settings


class SKUImageSerializer(serializers.ModelSerializer):
    '''
        SKU图片表的序列化器
    '''
    class Meta:
        model = SKUImage
        fields = ('id', 'sku', 'image')
    # 重写create方法, 把图片上传到fastDFS中
    def create(self, validated_data):
        # 1. 建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2. 获取图片数据 在序列化器中获取request
        request = self.context['request']
        image_file = request.data.get('image')
        # 3. 上传图片
        ret = client.upload_by_buffer(image_file.read())
        # 4. 判断返回结果
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5. 上传成功将返回的文件路径保存到图片表中
        image_url = ret['Remote file_id']
        sku_id = request.data['sku']
        img = SKUImage.objects.create(image=image_url, sku_id=sku_id)#sku_id=request.data['sku']

        # 获取sku对象
        sku = SKU.objects.get(pk=sku_id)
        if not sku.default_image:
            sku.default_image = image_url
            sku.save()
        # 生成新的详情页页面
        get_detail_html.delay(sku_id)
        # 6. 返回保存后的图片对象数据
        return img

    # 重写update方法，将图片上传到fasfDFS中
    def update(self, instance, validated_data):
        # 1. 建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 2. 获取图片数据 在序列化器中获取request
        request = self.context['request']
        image_file = request.data.get('image')
        # 3. 上传图片
        ret = client.upload_by_buffer(image_file.read())
        # 4. 判断返回结果
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 5. 上传成功将返回的文件路径更新到图片表中
        image_url = ret['Remote file_id']
        instance.image = image_url
        instance.sku_id = request.data['sku']
        instance.save()

        # 获取sku对象
        sku = SKU.objects.get(pk=instance.sku_id)
        if not sku.default_image:
            sku.default_image = image_url
            sku.save()
        # 生成新的详情页页面
        get_detail_html.delay(instance.sku_id)
        # 6. 返回保存后的图片对象数据
        return instance


class SKUSerializer(serializers.ModelSerializer):
    '''
        SKU简单数据序列化器
    '''
    class Meta:
        model = SKU
        fields = ('id', 'name')